package com.easy.leetcode.array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @ClassName FourSum18
 * @Description 18. 四数之和
 * @Author zheng
 * @Date 2021/10/21 18:47
 * @Version 1.0
 **/
public class FourSum18 {
    //18. 四数之和
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        //数组长度小于4或者第一个大于target，则不可能存在这样的四数之和
        if (nums.length < 4 || nums[0] > target) {
            return res;
        }
        int len = nums.length;
        for (int i = 0; i < len; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < len; j++) {
                if(j > i+1 && nums[j] == nums[j-1]){
                    continue;
                }
                int l = j + 1;
                int r = len - 1;
                while (l < r) {
                    //四数之和
                    int tmp = nums[i] + nums[j] + nums[l] + nums[r];
                    //等于0，存储当前值
                    if (tmp == target) {
                        List<Integer> list = new ArrayList<>();
                        list.add(nums[i]);
                        list.add(nums[j]);
                        list.add(nums[l]);
                        list.add(nums[r]);
                        res.add(list);
                        while (l < r && nums[l] == nums[l + 1]) {
                            l++;
                        }
                        while (l < r && nums[r] == nums[r - 1]) {
                            r--;
                        }
                        l++;
                        r--;
                    } else if (tmp > target) {
                        r--;
                    } else {
                        l++;
                    }
                }
            }
        }
        System.out.println(res.size());
        for (List<Integer> re : res) {
            System.out.println(re.toString());
        }
        return res;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{-2, -1, -1, 1, 1, 2, 2};
        FourSum18 fourSum18 = new FourSum18();
        fourSum18.fourSum(arr, 0);
    }
}
